package Teacher_Course_Student;

import Main.UserLogin;

import java.sql.*;

public class Teacher_Student {
    public static void course() throws Exception {
        // 1. 加载 JDBC 驱动
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        // 2. 获取数据库连接
        String url = "jdbc:sqlserver://localhost:1433;databaseName=Student_Grade_Management_System;trustServerCertificate=true";
        String user = "ysy";
        String password = "051018";
        Connection conn = DriverManager.getConnection(url, user, password);
        String teacher = UserLogin.getUsername();
        // 3. 定义 SQL 查询语句
        String sql = "SELECT * FROM 选课信息 where 教师姓名 = ?"; // 请确认表名是否正确
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, teacher);

        // 5. 执行 SQL 查询
        ResultSet rs = ps.executeQuery();

        // 获取列数
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 6. 打印列名
        for (int i = 1; i <= columnCount; i++) {
            System.out.print(metaData.getColumnName(i) + "\t");
        }
        System.out.println(); // 换行

        // 7. 打印数据
        while (rs.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String value = rs.getString(i);
                System.out.print(value + "\t");
            }
            System.out.println(); // 每行数据输出后换行
        }

        // 8. 关闭资源
        rs.close();
        conn.close();
    }
}
